import 'package:redux/redux.dart';
import '../models/user_model.dart';
import '../data/default_users.dart';

/// Redux用户状态
class ReduxUserState {
  final List<UserDataEntity> userCollection;
  final UserDataEntity? activeUser;

  const ReduxUserState({this.userCollection = const [], this.activeUser});

  ReduxUserState copyWith({
    List<UserDataEntity>? userCollection,
    UserDataEntity? activeUser,
  }) {
    return ReduxUserState(
      userCollection: userCollection ?? this.userCollection,
      activeUser: activeUser,
    );
  }
}

/// Redux用户动作
abstract class ReduxUserAction {}

class InitializeUserDataAction extends ReduxUserAction {
  final List<UserDataEntity> userList;
  InitializeUserDataAction(this.userList);
}

class UserLoginAction extends ReduxUserAction {
  final UserDataEntity user;
  UserLoginAction(this.user);
}

class UserRegisterAction extends ReduxUserAction {
  final UserDataEntity newUser;
  UserRegisterAction(this.newUser);
}

class UserLogoutAction extends ReduxUserAction {}

class UpdateUserAction extends ReduxUserAction {
  final UserDataEntity updatedUser;
  UpdateUserAction(this.updatedUser);
}

/// Redux用户Reducer
ReduxUserState userReducer(ReduxUserState state, dynamic action) {
  if (action is InitializeUserDataAction) {
    return state.copyWith(userCollection: action.userList);
  }
  if (action is UserLoginAction) {
    return state.copyWith(activeUser: action.user);
  }
  if (action is UserRegisterAction) {
    final updatedUsers = List<UserDataEntity>.from(state.userCollection)
      ..add(action.newUser);
    return state.copyWith(
      userCollection: updatedUsers,
      activeUser: action.newUser,
    );
  }
  if (action is UserLogoutAction) {
    return state.copyWith(activeUser: null);
  }
  if (action is UpdateUserAction) {
    final updatedUsers =
        state.userCollection.map((u) {
          return u.uniqueId == action.updatedUser.uniqueId
              ? action.updatedUser
              : u;
        }).toList();
    return state.copyWith(
      userCollection: updatedUsers,
      activeUser:
          state.activeUser?.uniqueId == action.updatedUser.uniqueId
              ? action.updatedUser
              : state.activeUser,
    );
  }
  return state;
}

/// Redux用户服务
class ReduxUserManager {
  static final ReduxUserManager _instance = ReduxUserManager._internal();
  factory ReduxUserManager() => _instance;
  ReduxUserManager._internal();

  Store<dynamic>? _store;

  void initialize(Store<dynamic> store) {
    _store = store;
  }

  Store<dynamic> get store {
    if (_store == null) throw Exception('User service not initialized');
    return _store!;
  }

  void initializeUserData() {
    store.dispatch(
      InitializeUserDataAction(DefaultUserCollection.defaultUserList),
    );
  }

  UserDataEntity? getCurrentUser() => store.state.userState.activeUser;
  bool isUserLoggedIn() => store.state.userState.activeUser != null;

  Future<bool> login(String loginAccount, String secretKey) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));
      final user = store.state.userState.userCollection.firstWhere(
        (u) => u.loginAccount == loginAccount && u.secretKey == secretKey,
        orElse: () => throw Exception('Account or password is incorrect'),
      );
      store.dispatch(UserLoginAction(user));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> register(UserDataEntity newUser) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));
      final existingUser = store.state.userState.userCollection.any(
        (u) => u.loginAccount == newUser.loginAccount,
      );
      if (existingUser) throw Exception('Account already exists');
      store.dispatch(UserRegisterAction(newUser));
      return true;
    } catch (e) {
      return false;
    }
  }

  void logout() => store.dispatch(UserLogoutAction());

  Future<bool> updateUser(UserDataEntity updatedUser) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(UpdateUserAction(updatedUser));
      return true;
    } catch (e) {
      return false;
    }
  }

  UserDataEntity? getUserById(String uniqueId) {
    try {
      return store.state.userState.userCollection.firstWhere(
        (u) => u.uniqueId == uniqueId,
      );
    } catch (e) {
      return null;
    }
  }

  UserDataEntity? getUserByAccount(String loginAccount) {
    try {
      return store.state.userState.userCollection.firstWhere(
        (u) => u.loginAccount == loginAccount,
      );
    } catch (e) {
      return null;
    }
  }

  List<UserDataEntity> getAllUsers() =>
      List.from(store.state.userState.userCollection);
  int getUserCount() => store.state.userState.userCollection.length;
}
